﻿using System.Web;
using Kiwi.Container.Application;
using Kiwi.Container.Scope;

namespace Kiwi.Container.Web
{
    public interface IHttpRequestContainerActivator : ILocalContainerActivator
    {
    }

    public class HttpRequestContainerActivator : IHttpRequestContainerActivator
    {
        private const string RequestItemKey = "HttpRequestContainerActivator.Container";
        public static readonly ILocalContainerActivator Default = new HttpRequestContainerActivator();

        #region IHttpRequestContainerActivator Members

        public IContainer GetLocalContainer(IContainer parentContainer)
        {
            var context = HttpContext.Current;
            if (context == null)
            {
                return null;
            }

            var container = GetRequestContainer(context);
            if (container != null)
            {
                return container;
            }

            container = parentContainer.CreateContainer(ContainerScope.HttpRequest);
            SetRequestContainer(context, container);

            return container;
        }

        #endregion

        private static IContainer GetRequestContainer(HttpContext context)
        {
            return context.Items[RequestItemKey] as IContainer;
        }

        private static void SetRequestContainer(HttpContext context, IContainer container)
        {
            context.Items[RequestItemKey] = container;
        }

        public static void ReleaseRequestContainer(HttpContext context)
        {
            var container = GetRequestContainer(context);
            if (container != null)
            {
                SetRequestContainer(context, null);
                container.Dispose();
            }
        }
    }
}